package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.emq.Topic;
import com.lkd.exception.LogicException;
import com.lkd.service.VendingMachineService;
import com.lkd.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * 完成工单更改售货机状态
 */
@Component
@Topic(TopicConfig.VMS_COMPLETED_TOPIC)
public class TaskCompletedMsgHandler implements MsgHandler {

    @Autowired
    private VendingMachineService vendingMachineService;

    @Override
    public void process(String jsonMsg) throws IOException {
        TaskCompleteContract contract = JsonUtil.getByJson(jsonMsg, TaskCompleteContract.class);
        // 如果数据为空，抛出异常
        if (null == contract || StringUtils.isEmpty(contract.getInnerCode())) {
            throw new LogicException("contract数据为空");
        }
        // 如果工单类型为投放工单，就把售货机状态改为运营
        if (contract.getTaskType() == VMSystem.TASK_TYPE_DEPLOY) {
            vendingMachineService.updateStatus(contract.getInnerCode(), VMSystem.VM_STATUS_RUNNING);
        }
        // 如果工单类型为撤销工单，就把售货机状态改为撤销
        if (contract.getTaskType() == VMSystem.TASK_TYPE_REVOKE) {
            vendingMachineService.updateStatus(contract.getInnerCode(), VMSystem.VM_STATUS_REVOKE);
        }
    }
}
